package com.supersit.GZFDA.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapStatusChangeListener;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.supersit.GZFDA.R;
import com.supersit.GZFDA.util.BaiDuMapUtils;
import com.supersit.GZFDA.util.BaiDuMapUtils.GetBaiduLocationResult;
import com.zhy.autolayout.AutoLayoutActivity;

public class BaiDuMapActivity extends AutoLayoutActivity implements
		GetBaiduLocationResult {
	private MapView mapView;
	private BaiduMap mBaiduMap;
	private BaiDuMapUtils baiDuMapUtils;
	private Context context;
	private double lat, lng;
	boolean isFirstLoc = true; // 是否首次定位
	private TextView tv_latitude, tv_longitude, tv_address;
	private Button btn_location;
	private LatLng mCenterLatLng;
	private Marker marker;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		// 在使用SDK各组件之前初始化context信息，传入ApplicationContext
		// 注意该方法要再setContentView方法之前实现
		SDKInitializer.initialize(getApplicationContext());
		setContentView(R.layout.activity_baidu_map);
		context = BaiDuMapActivity.this;
		initView();
		baiDuMapUtils = new BaiDuMapUtils(this, context, 0);
		baiDuMapUtils.startListener();
		bandListener();
	}

	private void bandListener() {
		mBaiduMap.setOnMapStatusChangeListener(onMapStatusChangeListener);
		btn_location.setOnClickListener(onClickListener);
		// mBaiduMap.setOnMarkerDragListener(onMarkerDragListener);
	}

	private void initView() {
		mapView = (MapView) findViewById(R.id.bmapView);
		mBaiduMap = mapView.getMap();
		// 普通地图
		mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
		// 开启定位图层
		mBaiduMap.setMyLocationEnabled(true);
		tv_latitude = (TextView) findViewById(R.id.tv_latitude);
		tv_longitude = (TextView) findViewById(R.id.tv_longitude);
		btn_location = (Button) findViewById(R.id.btn_location);
		tv_address = (TextView) findViewById(R.id.tv_address);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// 在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
		mapView.onDestroy();
		baiDuMapUtils.unRegisterLocationListener();
	}

	@Override
	protected void onResume() {
		super.onResume();
		// 在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
		mapView.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
		// 在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
		mapView.onPause();
	}

	@Override
	public void onReceiveLocation(BDLocation location) {
		// TODO Auto-generated method stub
		if (location != null)
			setStartLocation(location);
		else
			Toast.makeText(context, "定位失败", Toast.LENGTH_SHORT).show();
	}

	private OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			switch (arg0.getId()) {
			case R.id.btn_location:
				if (null != mCenterLatLng) {
					Intent intent = new Intent();
					intent.putExtra("lat", lat);
					intent.putExtra("lng", lng);
					intent.putExtra("address", tv_address.getText().toString());
					setResult(0, intent);
					finish();
				} else {
					Toast.makeText(context, "获取定位失败，请重新定位", Toast.LENGTH_SHORT)
							.show();
				}
				break;
			}
		}
	};

	/**
	 * 在地图上定位
	 * 
	 * @param location
	 */
	private void setStartLocation(BDLocation location) {
		// map view 销毁后不在处理新接收的位置
		if (location == null || mapView == null) {
			return;
		}
		lat = location.getLatitude();
		lng = location.getLongitude();
		mCenterLatLng = new LatLng(lat, lng);
		geoCodeInstance(mCenterLatLng);
		MyLocationData locData = new MyLocationData.Builder()
				.accuracy(location.getRadius())
				// 此处设置开发者获取到的方向信息，顺时针0-360
				.direction(100).latitude(location.getLatitude())
				.longitude(location.getLongitude()).build();
		mBaiduMap.setMyLocationData(locData);
		if (isFirstLoc) {
			isFirstLoc = false;
			LatLng ll = new LatLng(location.getLatitude(),
					location.getLongitude());
			MapStatus.Builder builder = new MapStatus.Builder();
			builder.target(ll).zoom(18.0f);
			mBaiduMap.animateMapStatus(MapStatusUpdateFactory
					.newMapStatus(builder.build()));
			tv_latitude.setText(lat + "");
			tv_longitude.setText(lng + "");
		}
	}

	/**
	 * 地图状态监听
	 */
	private OnMapStatusChangeListener onMapStatusChangeListener = new OnMapStatusChangeListener() {

		@Override
		public void onMapStatusChangeStart(MapStatus arg0) {
			// TODO Auto-generated method stub
			updateMapState(arg0);
		}

		@Override
		public void onMapStatusChangeFinish(MapStatus arg0) {
			// TODO Auto-generated method stub
			updateMapState(arg0);
			LatLng ll = arg0.target;
			geoCodeInstance(ll);
		}

		@Override
		public void onMapStatusChange(MapStatus arg0) {
			// TODO Auto-generated method stub
			updateMapState(arg0);

		}
	};

	private void updateMapState(MapStatus status) {
		mCenterLatLng = status.target;
		/** 获取经纬度 */
		lat = mCenterLatLng.latitude;
		lng = mCenterLatLng.longitude;
		tv_latitude.setText(lat + "");
		tv_longitude.setText(lng + "");
	}

	private void geoCodeInstance(LatLng latLng) {
		// 创建地理编码检索实例
		GeoCoder geoCoder = GeoCoder.newInstance();
		//
		OnGetGeoCoderResultListener listener = new OnGetGeoCoderResultListener() {
			// 反地理编码查询结果回调函数
			@Override
			public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
				if (result == null
						|| result.error != SearchResult.ERRORNO.NO_ERROR) {
					// 没有检测到结果
//					Toast.makeText(context, "抱歉，未能找到结果", Toast.LENGTH_LONG)
//							.show();
				} else {
					tv_address.setText(result.getAddress());
				}

			}

			// 地理编码查询结果回调函数
			@Override
			public void onGetGeoCodeResult(GeoCodeResult result) {
				if (result == null
						|| result.error != SearchResult.ERRORNO.NO_ERROR) {
					// 没有检测到结果
				}
			}
		};
		// 设置地理编码检索监听者
		geoCoder.setOnGetGeoCodeResultListener(listener);
		//
		geoCoder.reverseGeoCode(new ReverseGeoCodeOption().location(latLng));
		// 释放地理编码检索实例
		// geoCoder.destroy();
	}

}
